package com.learn.english.service.impl;

import com.learn.english.constants.CacheConstants;
import com.learn.english.enums.Category;
import com.learn.english.enums.ResultCode;
import com.learn.english.enums.TimeEnum;
import com.learn.english.exception.BusinessException;
import com.learn.english.mapper.CourseChapterMapper;
import com.learn.english.mapper.CourseMapper;
import com.learn.english.mapper.CourseVideoMapper;
import com.learn.english.model.entity.Course;
import com.learn.english.model.entity.CourseChapter;
import com.learn.english.model.entity.CourseVideo;
import com.learn.english.model.ro.CourseChapterRo;
import com.learn.english.model.ro.CourseInfoRo;
import com.learn.english.service.ICourseInfoService;
import com.learn.english.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author TISNIW
 * @version 1.0
 * @desc
 */
@Slf4j
@Service
public class CourseInfoServiceImpl implements ICourseInfoService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseChapterMapper courseChapterMapper;
    @Autowired
    private CourseVideoMapper courseVideoMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public CourseInfoRo detail(Integer courseId) {
        log.info("detail:{}", courseId);
        log.info("redis获取课程信息");
        CourseInfoRo courseInfoRo = redisService.getCacheObject(CacheConstants.COURSE_INFO_CACHE_KEY + courseId, CourseInfoRo.class);
        if (courseInfoRo == null){
            log.info("redis获取课程信息失败，从数据库获取");
            courseInfoRo = getCourseInfo(courseId);
        }
        if (courseInfoRo == null){
            log.warn("课程不存在");
            throw new BusinessException(ResultCode.COURSE_NOT_EXIST);
        }
        log.info("设置缓存");
        redisService.setCacheObject(CacheConstants.COURSE_INFO_CACHE_KEY + courseId, courseInfoRo, TimeEnum.ONE_DAY);
        return courseInfoRo;
    }

    private CourseInfoRo getCourseInfo(Integer courseId) {
        // 查询课程基本信息
        Course course = courseMapper.selectById(courseId);
        log.info("course:{}", course);
        if (course == null) {
            return null;
        }
        log.info("构建基础信息");
        // 构建基础信息
        CourseInfoRo courseInfoRo = CourseInfoRo.builder()
                .id(Long.valueOf(course.getId()))
                .category(Category.getNameFromId(course.getCategoryId()).orElse("未知分类"))
                .name(course.getName())
                .desc(course.getDesc())
                .courseUrl(course.getCourseUrl())
                .coverUrl(course.getCoverUrl())
                .isFree(course.getIsFree() != null && course.getIsFree())
                .cost(course.getCost())
                .count(course.getCount())
                .createdAt(course.getCreatedAt())
                .updatedAt(course.getUpdatedAt())
                .build();

        // 查询所有章节
        log.info("courseId:{}", courseId);
        List<CourseChapter> chapters = courseChapterMapper.findByCourseId(courseId);
        log.info("chapter size:{}", chapters.size());
        if (chapters == null || chapters.isEmpty()) {
            // 如果没有章节，则直接查询该课程下的所有视频作为顶层视频展示
            List<CourseVideo> videos = courseVideoMapper.findByCourseId(courseId);
            courseInfoRo.setCourseVideos(videos);
            return courseInfoRo;
        }

        // 存放章节 + 视频的 Ro 列表
        List<CourseChapterRo> chapterRoList = new ArrayList<>();

        for (CourseChapter chapter : chapters) {
            // 构建章节 Ro
            CourseChapterRo chapterRo = CourseChapterRo.builder()
                    .id(chapter.getId())
                    .title(chapter.getTitle())
                    .desc(chapter.getDesc())
                    .sort(chapter.getSort())
                    .isPublished(chapter.getIsPublished())
                    .createdAt(chapter.getCreatedAt())
                    .updatedAt(chapter.getUpdatedAt())
                    .build();
            log.info("chapterId:{}", chapter.getId());
            List<CourseVideo> videos = courseVideoMapper.findByChapterId(chapter.getId());
            chapterRo.setCourseVideos(videos);

            // 添加到最终结果中
            chapterRoList.add(chapterRo);
        }

        // 设置章节列表
        courseInfoRo.setCourseChapters(chapterRoList);

        return courseInfoRo;
    }
}
